package com.mc.designpattern.strategy.util;

import com.mc.designpattern.strategy.channelStrategy.ChannelStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/***
 * @ClassName HandleChannelContext
 * @Description todo
 * @Author CC
 * @Date: 2019/10/3011:51
 * @Version 1.0
 */
@Component
public class HandleChannelContext {
    @Autowired
    private ApplicationContext context;
    //存放所有策略类Bean的map
    private static Map<Integer, Class<ChannelStrategy>> strategyMap = new HashMap<>();

    /**
     * 为什么要单独提供这个方法
     * 如果strategyMap设置为public 通过 HandleChannelContext.strategyMap.put(channel, beanClass); 直接调用，可能会存在漏洞
     * 别人可以直接map.remove
     *
     * @return
     */
    public void strategyMapPut(Integer channel, Class<ChannelStrategy> clazz) {
        strategyMap.put(channel, clazz);
    }

    /**
     * 通过来源获取到对应的实例bean
     *
     * @param type
     * @return
     */
    public ChannelStrategy getStrategy(Integer type) {
        final Class<ChannelStrategy> strategyClass = strategyMap.get(type);
        if (strategyClass == null) {
            throw new UnsupportedOperationException("该来源没有配置策略");
        }
        return context.getBean(strategyClass);
    }
}
